package com.winit.uCloud.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.base.beans.LoginUser;
import com.winit.common.base.web.BaseController;
import com.winit.common.filter.UserInfoUtil;
import com.winit.common.util.Constants;
import com.winit.deploy.service.DeployService;
import com.winit.project.core.bean.EditionInfo;
import com.winit.project.manager.ProjectManager;
import com.winit.project.util.ProjectUtil;
import com.winit.uCloud.bean.UCloudInfo;
import com.winit.uCloud.manager.UCloudManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangjian on 16/10/28.
 */
@RestController
@RequestMapping("/uCloud")
public class UCloudController extends BaseController{

    private static Logger logger = LoggerFactory.getLogger(UCloudController.class);

    @Autowired
    private UCloudManager uCloudManager;
    @Autowired
    private ProjectManager projectManager;
    @Autowired
    private DeployService deployService;

    @RequestMapping("/getUCloudList")
    @ResponseBody
    public Map<String,Object> getUCloudList(HttpServletRequest request){
        Map<String,Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null){
            logger.error("com.winit.uCloud.web.UCloudController.getUCloudList,获取用户信息为空");
            return this.noUserRtn();
        }
        List<UCloudInfo> list = uCloudManager.getUCloudList();
        rtnMap.put("code","0");
        JSONObject object = new JSONObject();
        object.put("list",list);

        return this.getRtnMap(rtnMap,userInfo,object);
    }

    @RequestMapping("/getUCloudInfo")
    @ResponseBody
    public Map<String,Object> getUCloudInfo(HttpServletRequest request){
        Map<String,Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null){
            logger.error("com.winit.uCloud.web.UCloudController.getUCloudInfo,获取用户信息为空");
            return this.noUserRtn();
        }
        String name = request.getParameter("name");
        Assert.hasText(name,"虚拟机名为空");

        UCloudInfo info = uCloudManager.getUCloudInfo(name);
        JSONObject object = new JSONObject();
        if (info == null){
            rtnMap.put("code","1");
        }else {
            rtnMap.put("code","0");
            object.put("info",info);
        }
        return this.getRtnMap(rtnMap,userInfo,object);
    }

    @RequestMapping(value = "/saveUCloudInfo",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> saveUCloudInfo(HttpServletRequest request
            ,@RequestBody UCloudInfo info){
        Map<String,Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null){
            logger.error("com.winit.uCloud.web.UCloudController.saveUCloudInfo,获取用户信息为空");
            return this.noUserRtn();
        }

        Assert.isTrue(info != null,"虚拟机信息为空");
        boolean flag = uCloudManager.saveUCloudInfo(info);
        rtnMap.put("code",flag?0:1);
        rtnMap.put("desc",flag?"保存虚拟机信息成功":"保存虚拟机信息成功");
        return this.getRtnMap(rtnMap,userInfo,new JSONObject());
    }

    /**
     * 根据区域应用列表查询工程相关分支版本等信息
     * @param request
     * @return
     */
    @RequestMapping("/getUCloudProjectInfo")
    @ResponseBody
    public Map<String,Object> getUCloudProjectInfo(HttpServletRequest request){
        Map<String,Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null){
            logger.error("com.winit.uCloud.web.UCloudController.saveUCloudInfo,获取用户信息为空");
            return this.noUserRtn();
        }
        String param = request.getParameter("param");
        Assert.hasText(param,"工程列表为空");

        JSONArray array = JSONArray.parseArray(param);
        Assert.isTrue(array.size() != 0,"工程列表为空");

        List<JSONObject> list = uCloudManager.getUCloudProjectInfo(array);
        rtnMap.put("code","0");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);

        return this.getRtnMap(rtnMap,userInfo,jsonObject);
    }

    /**
     * 提交测试
     * @param request
     * @return
     */
    @RequestMapping("/uCloudToTest")
    @ResponseBody
    public Map<String,Object> uCloudToTest(HttpServletRequest request){
        Map<String, Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudController.uCloudToTest,获取用户信息为空");
            return this.noUserRtn();
        }
        String projectName = request.getParameter("projectName");
        String editionNum = request.getParameter("editionNum");
        String toTest = request.getParameter("toTest");
        Assert.hasText(projectName,"提交测试,projectName为空");
        Assert.hasText(editionNum,"提交测试,editionNum为空");
        Assert.hasText(toTest,"提交测试,toTest为空");

        //选中default提交测试时,先自动生成版本,然后将新版本提交测试
        if(ProjectUtil.BUILD_DIR.equals(editionNum)){
            try {
                editionNum = projectManager.createNewEdition(projectName,userInfo);
            } catch (Exception e) {
                logger.error("com.winit.uCloud.web.UCloudController.uCloudToTest,根据default创建新版本异常,projectName="+projectName,e);
                rtnMap.put("code","1");
                rtnMap.put("desc","根据default创建新版本异常。"+e.getMessage());
                return this.getRtnMap(rtnMap, userInfo, new JSONObject());
            }
        }
        JSONObject object = new JSONObject();
        try {
            boolean flag = projectManager.editionToTest(projectName,editionNum,Boolean.parseBoolean(toTest),userInfo);
            if(flag){
                rtnMap.put("code","0");
                object.put("editionNum",editionNum);
            }else {
                rtnMap.put("code","1");
                rtnMap.put("desc", "提交测试失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            rtnMap.put("code", 1);
            rtnMap.put("desc", e.getMessage());
        }finally {
            return this.getRtnMap(rtnMap, userInfo, object);
        }
    }

    /**
     * 测试通过
     * @param request
     * @return
     */
    @RequestMapping("/uCloudTestPass")
    @ResponseBody
    public Map<String,Object> uCloudTestPass(HttpServletRequest request){
        Map<String,Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudController.uCloudTestPass,获取用户信息为空");
            return this.noUserRtn();
        }
        String projectName = request.getParameter("projectName");
        String editionNum = request.getParameter("editionNum");
        String testStatus = request.getParameter("testStatus");
        Assert.hasText(projectName,"测试通过,projectName为空");
        Assert.hasText(editionNum,"测试通过,editionNum为空");
        Assert.hasText(testStatus,"测试通过,testStatus为空");

        try {
            if(!projectManager.isProjectExist(projectName)){
                logger.info("com.winit.uCloud.web.UCloudController.uCloudTestPass,工程不存在.projectName="+projectName);
                rtnMap.put("code","1");
                rtnMap.put("desc","工程不存在");
                return this.getRtnMap(rtnMap,userInfo,new JSONObject());
            }
            if(!projectManager.isEditionExist(projectName,editionNum)){
                logger.info("com.winit.uCloud.web.UCloudController.uCloudTestPass,版本不存在.projectName="+projectName+",editionNum="+editionNum);
                rtnMap.put("code","1");
                rtnMap.put("desc","工程版本不存在");
                return this.getRtnMap(rtnMap,userInfo,new JSONObject());
            }
        } catch (Exception e) {
            logger.error("com.winit.uCloud.web.UCloudController.uCloudTestPass 异常.projectName="+projectName+",editionNum="+editionNum,e);
            rtnMap.put("code","1");
            rtnMap.put("desc","测试通过异常.e:"+e.getMessage());
            return this.getRtnMap(rtnMap,userInfo,new JSONObject());
        }

        String status = Boolean.parseBoolean(testStatus)? Constants.PROJECT_EDITION_TEST_STATUS_PASS:Constants.PROJECT_EDITION_TEST_STATUS_NOT_PASS;

        try {
            boolean flag = deployService.updateProjectTestPassEdition(projectName,editionNum,status,userInfo);
            if(flag){
                rtnMap.put("code","0");
                rtnMap.put("desc","修改成功");
                return this.getRtnMap(rtnMap,userInfo,new JSONObject());
            }else{
                rtnMap.put("code","1");
                rtnMap.put("desc","修改失败");
                return this.getRtnMap(rtnMap,userInfo,new JSONObject());
            }
        } catch (Exception e) {
            logger.error("com.winit.uCloud.web.UCloudController.uCloudTestPass 异常.projectName="+projectName+",editionNum="+editionNum,e);
            rtnMap.put("code","1");
            rtnMap.put("desc","测试通过异常.e:"+e.getMessage());
            return this.getRtnMap(rtnMap,userInfo,new JSONObject());
        }
    }

    @RequestMapping("/adEditionList")
    @ResponseBody
    public Map<String, Object> adEditionList(HttpServletRequest request) {
        Map<String, Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudController.adEditionList,获取用户信息为空");
            return this.noUserRtn();
        }

        String projectName = request.getParameter("projectName");
        Assert.hasText(projectName, "com.winit.uCloud.web.UCloudController.adEditionList,工程名为空");

        JSONObject jsonObject = new JSONObject();
        List<EditionInfo> list = new ArrayList<>();
        try {
            list = uCloudManager.getAdVersion(projectName);
            rtnMap.put("code", "0");
        } catch (Exception e) {
            logger.error("获取工程版本信息列表异常.", e);
            rtnMap.put("code", "1");
            rtnMap.put("desc", "获取工程版本信息列表异常.e:" + e.getMessage());
        }
        jsonObject.put("list", list);
        return this.getRtnMap(rtnMap, userInfo, jsonObject);
    }

    /**
     * 检查工程配置文件是否正确
     * @param request
     * @return
     */
    @RequestMapping("/checkConfig")
    @ResponseBody
    public Map<String, Object> checkConfig(HttpServletRequest request) {
        Map<String, Object> rtnMap = new HashMap<>();
        LoginUser userInfo = UserInfoUtil.getUserInfo(request);
        if (userInfo == null) {
            logger.info("com.winit.uCloud.web.UCloudController.checkConfig,获取用户信息为空");
            return this.noUserRtn();
        }
        String projectName = request.getParameter("projectName");
        String envName = request.getParameter("envName");
        Assert.hasText(projectName, "com.winit.uCloud.web.UCloudController.checkConfig,工程名为空");
        Assert.hasText(envName, "com.winit.uCloud.web.UCloudController.checkConfig,环境名为空");
        logger.info("com.winit.uCloud.web.UCloudController.checkConfig projectName="+projectName+",envName="+envName);
        rtnMap.put("code","0");
        try {
            if(uCloudManager.checkConfig(projectName,envName)){
                rtnMap.put("desc","配置文件正确,可以进行发布.");
            }
        } catch (Exception e) {
            String msg = e.getMessage();
            if(!msg.startsWith("[ERROR]")){
                msg = "[ERROR]" + msg;
            }
            rtnMap.put("desc",msg);
        }
        return this.getRtnMap(rtnMap,userInfo,new JSONObject());
    }
}
